let form = layui.form, table = layui.table, $ = layui.jquery, id = getQueryVariable("id");

let colourList = getdictionary(6, 41);//颜色
let unitList = getdictionary(6, 42);//单位
//制单公司
let complaintUnit = [];
$.ajax({
    url: "company/getAllMakerUnit",
    success: function (res) {
        if (res.status == 200) {
            complaintUnit = res.data;
            $.each(res.data, function (index, item) {
                $("#complaintUnit").append(new Option(item.name, item.code));
            });
            form.render('select');
        } else {
            layer.msg(res.msg, {icon: 5});
        }
    }
});
//验货公司
$.ajax({
    url: "customer2/getAllInspectUnit",
    success: function (res) {
        if (res.status == 200) {
            $.each(res.data, function (index, item) {
                $("#company").append(new Option(item.name, item.code));
            });
            form.render('select');
        } else {
            layer.msg(res.msg, {icon: 5});
        }
    }
});

let loginUserCode = user.code;//当前登录用户编码
let executorList = [];
layer.ready(function () {
    $.ajax({
        url:"user/getAllUserNameAndCode",
        success:function(res){
            if(res.status == 200){
                executorList= res.data;
                for(let i in res.data){
                    $("#executor").append("<option value=\"" + res.data[i].code + "\">" + res.data[i].name + "</option>");
                    $("#inspector").append("<option value=\"" + res.data[i].code + "\">" + res.data[i].name + "</option>");
                }
                queryById();
                form.render('select');
            }else{
                layer.msg(res.msg, {icon: 5});
            }
        }
    });
});

let stageList = getdictionary(6,38);//验货阶段列表
let inspectTypeList = getdictionary(6,39);//验货类型列表
for(let i in stageList){
    $("#stageSelect").append("<option value=\"" + stageList[i].code + "\">" + stageList[i].name + "</option>");
}
for(let i in inspectTypeList){
    $("#inspectType").append("<option value=\"" + inspectTypeList[i].code + "\">" + inspectTypeList[i].name + "</option>");
}
form.render('select');

let productList = [];
let fileList = [
    {
        id: "1",
        fileName: "模拟图片",
        fileUrl: "statics/images/layui-logo.jpg",
        fileType: "jpg",
        fileSize: "1",
        executor: "admin",
        uploadTime: "2020-11-01"
    }
];
let logList = [
    {
        id: "1",
        operationtype: "text1",
        theoperator: "text2",
        operationdate: "text3",
        modifythecontent: "text4"
    }
];

$('#editor-form').find('input,textarea,select').attr('disabled', true);
//表单初始值
if (id != "") {
    form.val("editor-form", {
        "executor": "进入查看",
    })
}

//--验货质检明细
table.render({
    elem: '#storageproducts',
    id: 'storageproductstableid',
    data: productList,
    toolbar: '#storageproductstoolbar',
    cellMinWidth :120,
    cols: [[
        {checkbox: true},
        {field: 'productImg', title: '图片', align: 'center', templet: '#imgTpl'},
        {field: 'salesContractNo', title: '销售合同号', sort: true},
        {field: 'loadPlanNo', title: '出运计划单号', sort: true},
        {field: 'purchaseOrderNo', title: '采购单号', sort: true},
        {field: 'productNo', title: '产品编码', sort: true},
        {field: 'specNo', title: '规格编码', sort: true},
        {field: 'normExplain', title: '规格说明',style:"overflow:hidden" },
        {field: 'chineseName', title: '中文名称',style:"overflow:hidden" },
        {field: 'englishName', title: '英文名称',style:"overflow:hidden" },
        {field: 'chineseDesc', title: '中文描述',style:"overflow:hidden" },
        {field: 'englishDesc', title: '英文描述',style:"overflow:hidden" },
        {field: 'colour', title: '颜色',/* templet: '#colourScript',*/},
        {field: 'amount', title: '数量',
            templet: function(d){
                let amount = d.amount?d.amount:0.00; return Number(amount).toFixed(2);
            }
        },
        {field: 'unit', title: '单位', /*templet: '#unitScript',*/},
        {field: 'price', title: '销售单价',
            templet: function(d){
                let price = d.price?d.price:0.0000; return Number(price).toFixed(4);
            }},
        {field: 'unitCost', title: '成本单价',
            templet: function(d){
                let unitCost = d.unitCost?d.unitCost:0.0000; return Number(unitCost).toFixed(4);
            }
        },
        {field: 'priceSubtotal', title: '金额小计',
            templet: function(d) {
                if(d.amount==undefined || d.price==undefined){
                    return 0.00;
                }
                return (d.amount*d.price).toFixed(2);
            }
        },
        {field: 'supplier', title: '供应商名称'/*, templet: '#complaintUnitScript'*/},
        {field: 'productType', title: '产品类型',
            templet: function(d) {
                let name = "";
                if(d.productType){
                    if(d.productType==1){
                        name = "成品";
                    }else if(d.productType==1){
                        name = "配件";
                    }
                }
                return name;
            }
        },
    ]],
    page: true,
    limit:50,
    height: 380
    , done: function (res, curr, count) {
        let inspectorCode = $("#inspector").val();
        let loadPlanNos = $("#loadPlanNo").val();
        if(res.data.length>0){
            let companyId = res.data[0].companyId;
            if($("#complaintUnit").val()==""){
                $("#complaintUnit").append(new Option(companyId, companyId));
                $("#complaintUnit").val(companyId);
            }
            if(inspectorCode=="undefined" || inspectorCode==""){
                inspectorCode = res.data[0].inspectorCode;
            }
            if(loadPlanNos!=""){
                loadPlanNos+=",";
            }
            $.each(res.data, function (index, item) {
                if(item.loadPlanNo!=undefined){
                    if(loadPlanNos.indexOf(item.loadPlanNo) == -1){
                        loadPlanNos += item.loadPlanNo+",";
                    }
                }else{
                    if(item.purchaseOrderNo!=undefined){
                        if(loadPlanNos.indexOf(item.purchaseOrderNo) == -1){
                            loadPlanNos += item.purchaseOrderNo+",";
                        }
                    }
                }
            });
            if (loadPlanNos.indexOf(",")!=-1){
                loadPlanNos=loadPlanNos.substring(0,loadPlanNos.length-1);
            }
        }
        //业务员 取值第一个产品操作员
        $("#inspector").val(inspectorCode);
        //出运计划单号 拼接
        $("#loadPlanNo").val(loadPlanNos);
        form.render('select');
        hoverOpenImg();//显示大图
        // for (let i in colourList) {
        //     $('.colourSelect').append(new Option(colourList[i].name, colourList[i].code));
        // }
        // for (let i in unitList) {
        //     $('.unitSelect').append(new Option(unitList[i].name, unitList[i].code));
        // }
        // for (let i in complaintUnit) {
        //     $('.complaintUnitSelect').append(new Option(complaintUnit[i].name, complaintUnit[i].code));
        // }
        for (let i = 0; i < res.data.length; i++) {
            let tempId = res.data[i].tempId!=undefined?res.data[i].tempId:i;
            // $("#colour_" + tempId).val(res.data[i].colour);
            // $("#unit_" + tempId).val(res.data[i].unit);
            // $("#complaintUnit_" + tempId).val(res.data[i].supplier);
        }
        form.render('select');
    }
});

function hoverOpenImg() {
    let img_show = null; // tips提示
    $("body").delegate("td img", "mouseover", function () {
        let img = "<img class='img_msg' src='" + $(this).attr('src') + "' style='width:130px;' />";
        img_show = layer.tips(img, this, {
            tips: [2, 'rgba(41,41,41,.5)']
            , area: ['160px']
        });
    });
    $("body").delegate("td img", "mouseout", function () {
        layer.close(img_show);
    });
}

//---附件
table.render({
    elem: '#attachment'
    , data: fileList
    , toolbar: '#attachmenttoolbar'
    , cols: [[
        {field: 'wjName', title: '文件名称', fixed: true,style:"overflow:hidden"},
        {field: 'fileUrl', title: '文件路径', fixed: true,style:"overflow:hidden"},
        {field: 'fileType', title: '文件类型', fixed: true},
        {field: 'fileSize', title: '文件大小(KB)', fixed: true},
        {field: 'fileExecutor', title: '操作员', fixed: true,
            templet: function(data) {
                let name = "";
                $.each(executorList, function(index, item) {
                    if (data.fileExecutor==item.code){
                        name = item.name;
                        return ;
                    }
                });
                return name;
            }
        },
        {field: 'fileUploadTime', title: '上传时间', fixed: true,
            templet: function(d) {
                return layui.util.toDateString(d.createTime,"yyyy-MM-dd");
            }
        },
        {fixed: 'right', width: 180, align: 'center', toolbar: '#attachmenteditor', title: '操作'},
    ]]
    , id: 'attachmenttableid'
    , height: 380
    , page: true
});

table.on('tool(attachmenttable)', function (obj) {
    let data = obj.data;
    if (obj.event === 'download') { //下载
        downFileLoad(data.fileUrl+'/'+data.fileName);
    }
});

//---操作日志
table.render({
    elem: '#otherwarehouselog'
    , data: logList
    , cols: [[
        {field: 'operationtype', title: '操作类型', fixed: true}
        , {field: 'theoperator', title: '操作员'}
        , {field: 'operationdate', title: '操作日期'}
        , {field: 'modifythecontent', title: '修改内容'}
    ]]
    , id: 'logtableid'
    , height: 380
    , limit: 30//显示的数量
    , page: true
});
$("#shutdown").on("click", function () {
    //关闭此页面
    parent.detab("views/jsp/other/tpl/viewinspection.jsp" + (id == '' ? '' : '?id=' + id));
});


function queryById() {
    $.ajax({
        type: 'POST',
        // data:{"id":id},
        url: 'inspectCargo/selectByKey/' + id,
        dataType: "json",
        contentType: 'application/json;charset=utf-8',
        async: false,
        success: function (res) {
            if (res.status == 200) {
                if(res.data){
                    form.val("editor-form", {
                        "oddNumber": res.data.oddNumber,
                        "inspectType": res.data.inspectType,
                        "inspectTime": res.data.inspectTime,
                        "address": res.data.address,
                        "timeLimit": res.data.timeLimit,
                        "reportNo": res.data.reportNo,
                        "loadPlanNo": res.data.loadPlanNo,
                        "inspector": res.data.inspector,
                        "cost": res.data.cost,
                        "stage": res.data.stage,
                        "complaintUnit": res.data.complaintUnit,
                        "executor": res.data.executor,
                        "remark": res.data.remark,
                        "company":res.data.company
                    });
                    productList = queryProductByIcId(id);
                    table.reload('storageproductstableid',{data : productList});
                    fileList = queryFileByIcId(id);
                    table.reload('attachmenttableid',{data : fileList});
                }else{
                    layer.msg("初始化失败!");
                }
            } else {
                layer.msg("初始化失败!");
            }
        },
        error: function (data) {
            layer.msg("初始化失败!");
        }
    });
}

//产品
function queryProductByIcId(icId) {
    let obj = [];
    $.ajax({
        type: 'POST',
        url: 'inspectCargo/selectProductByIcId/'+icId,
        dataType: "json",
        contentType: 'application/json;charset=utf-8',
        async: false,
        success: function (res) {
            if (res.status == 200) {
                if(res.data.length>0){
                    obj = res.data;
                    form.val("editor-form", {
                        "productNo": res.data.productNo,
                        "specNo": res.data.specNo,
                        "normExplain": res.data.normExplain,
                        "chineseName": res.data.chineseName,
                        "englishName": res.data.englishName,
                        "chineseDesc": res.data.chineseDesc,
                        "englishDesc": res.data.englishDesc,
                        "unit": res.data.unit,
                        "colour": res.data.colour,
                        "customerArticleNo": res.data.customerArticleNo,
                        "price": res.data.price,
                        "amount": res.data.amount,
                        "priceSubtotal": res.data.priceSubtotal,
                        "supplier": res.data.supplier,
                        "unitCost": res.data.unitCost,
                        "salesContractNo": res.data.salesContractNo,
                        "purchaseOrderNo": res.data.purchaseOrderNo,
                    })
                }else{
                    // layer.msg(res.msg, {icon : 0})
                }
            }else{
                layer.msg("产品初始化失败!");
            }
        },
        error: function (data) {
            layer.msg("产品初始化失败!");
        }
    });
    return obj;
}
//附件
function queryFileByIcId(icId) {
    let obj = [];
    $.ajax({
        type: 'POST',
        url: 'inspectCargo/selectFileByIcId/'+icId,
        dataType: "json",
        contentType: 'application/json;charset=utf-8',
        async: false,
        success: function (res) {
            if (res.status == 200) {
                if (res.data.length>0){
                    obj = res.data;
                    form.val("editor-form", {
                        "wjName": res.data.wjName,
                        "fileUrl": res.data.fileUrl,
                        "fileType": res.data.fileType,
                        "fileSize": res.data.fileSize,
                        "executor": res.data.executor,
                        "uploadTime": res.data.uploadTime,
                    })
                }else{
                    // layer.msg("暂无附件数据",{icon:3});
                }
            }else{
                layer.msg(res.msg,{icon:3});
            }
        },
        error: function (data) {
            layer.msg("附件初始化失败!");
        }
    });
    return obj;
}
